package com.note.chh.notebook.Uitls;

import android.content.Context;
import android.content.res.ColorStateList;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.text.Editable;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.style.TextAppearanceSpan;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

import com.note.chh.notebook.Api.Constant;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * Created by Administrator on 2015/12/1.
 */
public class UserUtil {

    //格式化int类型的数据
    public static String price(int price){
        DecimalFormat df = new DecimalFormat("0.00");
        String format = df.format(price);
        return format;
    }
    //格式化double类型的数据
    public static String price(double price){
        DecimalFormat df = new DecimalFormat("0.00");
        String format = df.format(price);
        return format;
    }
    //格式化为3位的double类型数据 tdd
    public static String tdd(double b){
        DecimalFormat df = new DecimalFormat("0.000");
        String format = df.format(b);
        return format;
    }

    public static String times(){
        SimpleDateFormat formatter    =   new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date curDate    =   new Date(System.currentTimeMillis());//获取当前时间
        String str    =    formatter.format(curDate);
        return str;
    }

    public static String times(long time){
        SimpleDateFormat formatter    =   new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date curDate    =   new Date(time);//获取当前时间
        String str    =    formatter.format(curDate);
        return str;
    }
    /*
     *时间换算
     */
    public static String timedata(String time){
        //2015/11/6 10:05:52
        Calendar c = Calendar.getInstance();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat format_info = new SimpleDateFormat("MM-dd");
        Date date = null;
        try {
            date = format.parse(time);
            c.setTime(date);
            long times= System.currentTimeMillis()-c.getTimeInMillis();
            if(times>60*60*24*1000){
                if((times/(60*60*24*1000))>9){
                    return format.format(c.getTimeInMillis()).split(" ")[0];
                }else{
                    return (times/(60*60*24*1000))+"天前";
                }
            }else if(times>60*60*1000){
                return (times/(60*60*1000))+"小时前";
            }else if(times>60*1000){
                return (times/(60*1000))+"分钟前";
            }else{
                return "刚刚";
            }
        } catch (Exception e) {
            return "未知";
        }
    }

    //邮箱验证
    public static boolean isEmail(String strEmail) {
        String strPattern = "^[a-zA-Z0-9][\\w\\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\\w\\.-]*[a-zA-Z0-9]\\.[a-zA-Z][a-zA-Z\\.]*[a-zA-Z]$";
        if (TextUtils.isEmpty(strPattern)) {
            return false;
        } else {
            return strEmail.matches(strPattern);
        }
    }
    /**
     * 将html文本内容中包含img标签的图片，宽度变为屏幕宽度，高度根据宽度比例自适应
     **/
    /*public static String getNewContent(String htmltext){
        try {
            Document doc= Jsoup.parse(htmltext);
            Elements elements=doc.getElementsByTag("img");
            for (Element element : elements) {
                element.attr("width","100%").attr("height","auto");
            }
            return doc.toString();
        } catch (Exception e) {
            return htmltext;
        }
    }*/

    /**
     * 限制小数点后两位小数
     */
    public static void setPricePoint(final EditText editText){
        editText.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.toString().contains(".")) {
                    if (s.length() - 1 - s.toString().indexOf(".") > 2) {
                        s = s.toString().subSequence(0, s.toString().indexOf(".") + 3);
                        editText.setText(s);
                        editText.setSelection(s.length());
                    }
                }
                if (s.toString().trim().substring(0).equals(".")) {
                    s = "0" + s;
                    editText.setText(s);
                    editText.setSelection(2);
                }
                if (s.toString().startsWith("0") && s.toString().trim().length() > 1) {
                    if (!s.toString().substring(1, 2).equals(".")) {
                        editText.setText(s.subSequence(0, 1));
                        editText.setSelection(1);
                        return;
                    }
                }
            }
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }
            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    /**
     * 限制小数点后一位小数
     */
    public static void setOnePoint(final EditText editText){
        editText.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.toString().contains(".")) {
                    if (s.length() - 1 - s.toString().indexOf(".") > 1) {
                        s = s.toString().subSequence(0, s.toString().indexOf(".") + 2);
                        editText.setText(s);
                        editText.setSelection(s.length());
                    }
                }
                if (s.toString().trim().substring(0).equals(".")) {
                    s = "0" + s;
                    editText.setText(s);
                    editText.setSelection(2);
                }
                if (s.toString().startsWith("0") && s.toString().trim().length() > 1) {
                    if (!s.toString().substring(1, 2).equals(".")) {
                        editText.setText(s.subSequence(0, 1));
                        editText.setSelection(1);
                        return;
                    }
                }
            }
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }
            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    /**
     *EditText中获取焦点输入框内容为0时清空 （输入必须是数字）
     */
    public static void setEditTextEmpty(final EditText editText){
        editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                Log.d("chh","------------------onFocusChange2"+hasFocus);
                if (hasFocus&&!editText.getText().toString().equals("")&& Double.parseDouble(editText.getText().toString())==0) {
                    editText.setText("");
                }
            }
        });
    }

    /**
     * 获取焦点后，光标置于末尾
     */
    public static void setEditSelection(final EditText editText){
        editText.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }
            @Override
            public void afterTextChanged(Editable s) {
                if (!s.toString().isEmpty()) {
                    editText.setSelection(s.toString().length());
                }
            }
        });
    }

    /**
     * 打开软键盘
     */
    public static void openKeybord(EditText mEditText, Context mContext) {
        InputMethodManager imm = (InputMethodManager) mContext
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(mEditText, InputMethodManager.RESULT_SHOWN);
        imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,
                InputMethodManager.HIDE_IMPLICIT_ONLY);
    }

    /**
     * 关闭软键盘
     */
    public static void closeKeybord(EditText mEditText, Context mContext) {
        InputMethodManager imm = (InputMethodManager) mContext
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(mEditText.getWindowToken(), 0);
    }

    /**
     * 格式化时间 （年-月-日  时）
     */
    public static String FormatTime(String time){
       return time.equals("")||time.length()<13?"":time.substring(0,11)+"("+ Integer.parseInt(time.substring(11,13))+"点)";
    }

    /**
     * 将long类型的时间转换为日-时-分
     */
    public static String ToDayHourMinute(long time){
        int time1 = (int) (time/(1000*60));//分
        if (time1==60) {
            return "0-1-0";
        }else if(time1<60){
            return "0-0-"+time1;
        }else{
            int time2 = time1/60;//时
            int time3 = time1%60;//分
            if (time2==24) {
                return "1-0-"+time3;
            }else if(time2<24){
                return "0-"+time2+"-"+time3;
            }else{
                int time4 = time2/24;//天
                int time5 = time2%24;//时
                return time4+"-"+time5+"-"+time3;
            }
        }
    }

    /**
     * 将long类型的时间转换为日-时-分-秒
     */
    public static String ToDayHourMinuteSecond(long time){
        int time1 = (int) (time/(1000*60));//分
        int time0 = (int) ((time%(1000*60))/1000);//秒
        if (time1==60) {
            return "0-1-0-"+time0;
        }else if(time1<60){
            return "0-0-"+time1+"-"+time0;
        }else{
            int time2 = time1/60;//时
            int time3 = time1%60;//分
            if (time2==24) {
                return "1-0-"+time3+"-"+time0;
            }else if(time2<24){
                return "0-"+time2+"-"+time3+"-"+time0;
            }else{
                int time4 = time2/24;//天
                int time5 = time2%24;//时
                return time4+"-"+time5+"-"+time3+"-"+time0;
            }
        }
    }

    /**
     * 自定义String字符串中某一段字符的颜色
     */
    public static String ColorText(String color, String Content){
        return "<font color = '"+color+"'>"+Content+"</font>";
    }

    /**
     *同时改变字符串中的字体大小和颜色
     * @return
     */
    public static SpannableStringBuilder sizeAndColor(String cotent,int color,int size,int start,int end){
        ColorStateList colors = ColorStateList.valueOf(color);//0xffff0000
        SpannableStringBuilder spanBuilder = new SpannableStringBuilder(cotent);
        //style 为0 即是正常的，还有Typeface.BOLD(粗体) Typeface.ITALIC(斜体)等
        //size  为0 即采用原始的正常的 size大小
        spanBuilder.setSpan(new TextAppearanceSpan(null, 0, size, colors, null), start, end, Spanned.SPAN_EXCLUSIVE_INCLUSIVE);

//        TextView tv_test = (TextView) findViewById(R.id.tv_test);
//        tv_test.setText(spanBuilder);
        return spanBuilder;
    }

    /**
     * Log d日志
     */
    public static void dLog(String log){
        if (Constant.ISDEBUG) {
            Log.d(Constant.LOGNAME,log);
        }
    }

    /**
     *错误日志
     */
    public static void eLog(String log){
        if (Constant.ISDEBUG) {Log.e(Constant.LOGNAME,log);}
    }

    /**
     * 判断网络连接是否可用
     */
    public static boolean isNetworkConnected(Context context) {
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context
            .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
            if (mNetworkInfo != null) {
                return mNetworkInfo.isAvailable();
            }
        }
        return false;
    }

    /**
     *equals比较对象
     *constant 常量
     *obj 被比较的对象
     */
    public static boolean toEquals(Object constant, Object obj){
        if (constant==null||obj==null) {
            new NullPointerException("Object为null");
        }else{
            return constant.equals(obj);
        }
        return false;
    }

    /**
     <xliff:g>标签介绍：属性id可以随便命名   属性值举例说明  %1$d  &2$d
     %n$ms：代表输出的是字符串，n代表是第几个参数，设置m的值可以在输出之前放置空格
     %n$md：代表输出的是整数，n代表是第几个参数，设置m的值可以在输出之前放置空格，也可以设为0m,在输出之前放置m个0
     %n$mf：代表输出的是浮点数，n代表是第几个参数，设置m的值可以控制小数位数，如m=2.2时，输出格式为00.00
     也可简单写成： %s（表示字符串）    %d（表示整数）    %f（表示浮点数）
     */
    public static String intFormat(String format, int num){
        return String.format(format, num);
    }
    public static String strFormat(String format, String content){
        return String.format(format, content);
    }

    /**
     * 信息太长,分段打印
     * @param tag
     * @param msg
     */
    public static void i(String tag, String msg) {
        //因为String的length是字符数量不是字节数量所以为了防止中文字符过多，
        //  把4*1024的MAX字节打印长度改为2001字符数
        int max_str_length = 2001 - tag.length();
        //大于4000时
        while (msg.length() > max_str_length) {
            Log.i(tag, msg.substring(0, max_str_length));
            msg = msg.substring(max_str_length);
        }
        //剩余部分
        Log.i(tag, msg);
    }

}
